package cn.yqm.frame.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.yqm.frame.action.Action;
import cn.yqm.frame.template.FormPack;
import cn.yqm.frame.template.FormTemplate;
import cn.yqm.frame.xmlParse.XmlBeans.XmlAction;
import cn.yqm.frame.xmlParse.XmlBeans.XmlBean;
import cn.yqm.frame.xmlParse.XmlBeans.XmlPackage;
import cn.yqm.frame.xmlParse.XmlBeans.XmlResult;

public class ActionServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		
		//封装页面传递过来的模板对象
		XmlBean xmlBean = (XmlBean)req.getSession().getServletContext().getAttribute("xmlConfig");
		
		//调用具体模板action做请求处理
		//根据请求的路径获取对应package及对应的action
		String servletPath = req.getServletPath();
		servletPath = servletPath.substring(1, servletPath.lastIndexOf(".do"));
		//用/区分package和action
		String pacName = servletPath.split("\\/")[0];
		String actionName = servletPath.split("\\/")[1];
		
		String beanClass = null;
		String classPath = null;
		XmlAction dealAction = null;
		List<XmlPackage> xmlPackages = xmlBean.getPackages();
		for (XmlPackage xmlPackage : xmlPackages) {
			if(pacName.equals(xmlPackage.getName())){
				List<XmlAction> xmlActions = xmlPackage.getXmlActions();
				for (XmlAction xmlAction : xmlActions) {
					if(actionName.equals(xmlAction.getName())){
						dealAction = xmlAction;
						beanClass = xmlAction.getBeanClass();
						classPath = xmlAction.getClassPath();
						break;
					}
				}
			}
		}
		
		FormTemplate formTemplate = FormPack.reflexPack(beanClass, req);
		try {
			Class<Action> actionClass = (Class<Action>)Class.forName(classPath);
			Action action = actionClass.newInstance();
			String returnStr = action.execute(req, formTemplate);
			
			String forwardPath = "";
			for (XmlResult xmlResult : dealAction.getResults()) {
				if(returnStr.equalsIgnoreCase(xmlResult.getName())){
					forwardPath = xmlResult.getForwardPath();
				}
			}
			req.getRequestDispatcher(forwardPath).forward(req, resp);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
}
